package com.bee.剑指offer;


/**
 * 在一个排序的链表中，存在重复的结点，请删除该链表中重复的结点，重复的结点不保留，返回链表头指针。 例如，链表1->2->3->3->4->4->5 处理后为 1->2->5
 * 该节点是排好序的
 *
 * 方法一：价格不重复的节点，重新串成一张链表
 *
 * @author yong
 * @date 2021-10-27
 */
public class 删除链表中重复的结点 {

    public static ListNode deleteDuplication(ListNode pHead) {
        ListNode dum = new ListNode(-1);
        ListNode point = dum;
        while (pHead != null) {
            // 当前节点，后面的元素为null，或者后面的元素和当前元素不相同，即保留这个节点
            if(pHead.next == null || pHead.next.val != pHead.val) {
                point.next = pHead;
                point = pHead;
            }
            // 如果与到了当前节点和下一个节点相同，即跳过，不保留
            while (pHead.next != null && pHead.val == pHead.next.val) {
                pHead = pHead.next;
            }
            pHead = pHead.next;
        }
        // 最后一个节点需要置为空null
        point.next = null;
        return dum.next;
    }

    public static ListNode deleteNode(ListNode pHead) {
        if(pHead == null) {
            return pHead;
        }
        ListNode dum = new ListNode(-1);
        ListNode point = dum;
        while (pHead != null) {
            if(pHead.next == null || pHead.val != pHead.next.val) {
                point.next = pHead;
                point = pHead;
            }
            while (pHead.next != null && pHead.next.val == pHead.val) {
                pHead = pHead.next;
            }
            pHead = pHead.next;
        }
        point.next = null;
        return dum.next;
    }

    public static void main(String[] args) {
        ListNode root = new ListNode(1);
        root.next = new ListNode(2);
        root.next.next = new ListNode(3);
        root.next.next.next = new ListNode(3);
        root.next.next.next.next = new ListNode(4);
        root.next.next.next.next.next = new ListNode(5);
        ListNode listNode = deleteDuplication(root);
        while (listNode != null) {
            System.out.print(listNode.val + "\t");
            listNode = listNode.next;
        }
    }

}
